package com.vinaprime.primeschedule.presentation;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioEncoder;
import android.media.MediaRecorder.AudioSource;
import android.media.MediaRecorder.OutputFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.vinaprime.primeschedule.businesslayer.VPSnoozeSound_BL;
import com.vinaprime.primeschedule.entities.VPSnoozeSound;

public class VPSnoozeSoundActivity extends Activity {
	public final static String SOUND_ID = "com.vinaprime.primeschedule.presentation.MESSAGE";
	
	int _idSound;
	int _position = 0;	
	List<VPSnoozeSound> listSound;
	List<VPSnoozeSound> listSoundFilter;
    ListView listView;
    ListViewSnoozeSoundAdapter list_adapter;
    VPSnoozeSound_BL soundBL;
    ApplicationInformation appInfo;
    String path;
    SearchView _searchview;   
    Uri uriSound;
    String FileName;
    private static final int SOUND_SELECT =1;
    private static final int SOUND_RECORD =2;
    ////Media Player
    MediaPlayer myPlayer;
    ImageButton imagebtnMute;
    ImageButton imagebtnPlay;
    ImageButton imagebtnPrevious;
    ImageButton imagebtnNext;
    ImageButton imagebtnAdd;
    TextView tvTimeline;
    TextView tvFileName;
    SeekBar processbar;
    Handler handler;
    Timer timer;
    private int current = 0;     
    private int duration = 0;     
	int positionseek = 0; //Dung de xac dinh vi tri khi pause
	boolean ismute = false;	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpsnoozesound);
		//Set action bar
		ActionBar actionBar = getActionBar();
		//Drawable d=getResources().getDrawable(R.raw.background_top);  
		//actionBar.setBackgroundDrawable(d);
    	actionBar.hide();		
				//Khoi tao doi tuong		
		initialize();
		//Khoi tao listview
		showlistview();
		
		/* Set Listener cho cac doi tuong
		 * GiangVH
		 */
		 //Mute button
		imagebtnMute.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
								
				onMuteSound(ismute);
				ismute = !ismute;
			}
		});
	     //play button
	    imagebtnPlay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if (listSound.size()>0){
					
					onStartSound(_position);
				}
			
					
			}
		});
		///next button
		imagebtnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
											
				if (listSound.size()>0){				
				
					try {
		
							onStopSound();
						} catch (Exception e) {			
							e.printStackTrace();
						};				
						int last;					
						last = listView.getLastVisiblePosition();	
						if(_position < last ){
							_position = _position +1;
							onStartSound(_position);					
						}else{
							_position = 0;
							onStartSound(_position);
						}
						
						list_adapter.setMyLastSelectedPostition(_position);
						
						listView.setSelection(_position);
						listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
						listView.setItemChecked(_position, true);
					}
			}
		});
		//previous button
		imagebtnPrevious.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (listSound.size()>0){				
					try {					
						onStopSound();
					} catch (Exception e) {					
						e.printStackTrace();
					};		
					int last;					
					last = listView.getLastVisiblePosition();	
					if (_position >0){					
						_position = _position-1;
						onStartSound(_position);					
					}else{
						_position = last;
						onStartSound(_position);	
					}
					
					list_adapter.setMyLastSelectedPostition(_position);
					
					listView.setSelection(_position);
					listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
					listView.setItemChecked(_position, true);
				}
			}			
		});
		imagebtnAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//onReplay();
				showDialogCustom();
			}
		});
		processbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
	
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {	}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {					
				if(fromUser){  
					if (!myPlayer.isPlaying())
					{	
						onStartSound(_position);					 
					}
					myPlayer.seekTo(progress);	                
					
	            } 	
				UpdateTimeWhenPlay();
					
			}
		})	;		
		//timer
		timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {						
						String tmp;
						tmp = tvFileName.getText().toString().substring(1);
						String tmp2= tvFileName.getText().toString().substring(0, 1);
						tvFileName.setText(tmp + tmp2);
						/*Dung cho seekbar va gio*/
						if (myPlayer.isPlaying()){							
								if(processbar != null){
									processbar.setProgress(myPlayer.getCurrentPosition());
								}								
							//	UpdateTimeWhenPlay();
							
						}					
					}
				});
			}
		}, 0, 1000);
	
	}
	
	@SuppressWarnings("deprecation")
	public void initialize(){
		/*Khoi tao du lieu, duong dan*/		
		appInfo = new ApplicationInformation(this);
		path = appInfo.getDBPath();
		soundBL = new VPSnoozeSound_BL(this, path+ "databases/");
		
		/* Khoi tao doi tuong in mediaplayer
		 * GiangVH
		 */
		myPlayer = (MediaPlayer)getLastNonConfigurationInstance();
        //If not, make a new one
        if (myPlayer == null) {
        	myPlayer = new MediaPlayer();
           //...Set up new player instance...
        }
		 System.out.print("Khoi Tao media Player");
		 // myPlayer.setOnPreparedListener(this);  
		 imagebtnMute = (ImageButton)findViewById(R.id.ibtnMute);
		 imagebtnMute.setBackgroundResource(android.R.drawable.ic_lock_silent_mode_off);
	     imagebtnPlay = (ImageButton)findViewById(R.id.ibtnPlay);
	     imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);
	     imagebtnPrevious = (ImageButton)findViewById(R.id.ibtnPrevious);
	     imagebtnNext = (ImageButton)findViewById(R.id.ibtnNext);
	     imagebtnAdd = (ImageButton)findViewById(R.id.ibtnAdd);
	     handler =  new Handler();
	     tvTimeline = (TextView)findViewById(R.id.tvtimeline);
	     Log.w("Khoi Tao Textview time line", "Hoan Thanh");
	     processbar = (SeekBar)findViewById(R.id.songProgressBar);		    
	     Log.w("Khoi Tao Textview time line", "Hoan Thanh");
	     tvFileName = (TextView)findViewById(R.id.tvfilename);
	     tvFileName.setText("VinaPrime  ");
	     timer  = new Timer();	     
	    
	    
	}	
		    
	public void onStopSound() {   
	
	    if (myPlayer.isPlaying())
	    	myPlayer.stop();    
		    
		positionseek = 0;
		imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);			

	}
	public void onMuteSound(boolean ismute) { 
		AudioManager manager = (AudioManager)getSystemService(AUDIO_SERVICE);		
		if (ismute) {
			manager.setStreamMute(AudioManager.STREAM_MUSIC, false);
			imagebtnMute.setBackgroundResource(android.R.drawable.ic_lock_silent_mode_off);
		}else {
			manager.setStreamMute(AudioManager.STREAM_MUSIC, true);
			imagebtnMute.setBackgroundResource(android.R.drawable.ic_lock_silent_mode);
		}
	}
	
	public void onStartSound(int position){	
		
		if (myPlayer.isPlaying()){
			positionseek = myPlayer.getCurrentPosition();
			myPlayer.pause();			
			imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);
		}
		else{						
				if (positionseek == 0){	
					try {
						
						if (myPlayer != null)
						{							
							myPlayer.release();
							myPlayer = null;	
						}
						myPlayer = new MediaPlayer();
						myPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
						myPlayer.setDataSource(path+"sounds/"+listSound.get(position).getVpssFilePath());
						myPlayer.prepare(); 
						myPlayer.start();
						
						duration = myPlayer.getDuration();  
						
						processbar.setMax(duration);  						
														
						//set filename
						tvFileName.setText(listSound.get(position).getVpssFilePath() + "     ");
						
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
						
				}else{					
					myPlayer.seekTo(positionseek);			              
					myPlayer.start();
					positionseek = 0;					
				}
				imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_pause);				 
				
		}
		
		list_adapter.setMyLastSelectedPostition(_position);
		
		listView.setSelection(_position);
		listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);		
		listView.setItemChecked(_position, true);
	}		
	public void onReplay(){
		if (myPlayer.isPlaying()){
			myPlayer.stop();
			myPlayer.reset();
			imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);
		}
		
		try {	
			if (positionseek > 0){
				myPlayer.stop(); 
				myPlayer.reset(); 
			}				
			myPlayer.setDataSource(path+"sounds/"+listSound.get(_position).getVpssFilePath());
			myPlayer.prepare(); 
			//processbar
			duration = myPlayer.getDuration();  
			
			processbar.setMax(duration);  
			
			myPlayer.start();
						
			
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_pause);	
	}	
	
	private void UpdateTimeWhenPlay(){
		//do{
			current = myPlayer.getCurrentPosition();
			int cSecond = (int) (current/1000)%60;
			int cMinute = (int) ((current/1000)/60)%60;
			int cHour = (int) (((current/1000)/60)/60)%60;
			////
			int dSecond = (int) (duration/1000)%60;
			int dMinute = (int) ((duration/1000)/60)%60;
			int dHour = (int) (((duration/1000)/60)/60)%60;			
			if (dHour ==0 ){
				tvTimeline.setText(String.format("%02d:%02d/%02d:%02d", cMinute,cSecond,dMinute, dSecond));
			}else{
				tvTimeline.setText(String.format("%02d:%02d:%02d/%02d:%02d:%02d", cHour, cMinute, cSecond, dHour, dMinute, dSecond));
			}
			
			String tmp1, tmp2;
			tmp1 = String.format("%02d:%02d", cMinute,cSecond);
			tmp2 = String.format("%02d:%02d",dMinute, dSecond);
			if(tmp1.equals(tmp2))
			{
				processbar.setProgress(0);
				imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play);
				
			}
			 
		//}while (processbar.getProgress() <= processbar.getMax());
	}
	public void showlistview(){
		listSound = soundBL.getAllSound();
		listView = (ListView)findViewById(R.id.listView_SnoozeSound);		
		list_adapter = new ListViewSnoozeSoundAdapter(listSound, this);
		listView.setAdapter(list_adapter);		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {				
				if( !String.valueOf(listSound.get(position).getVpssId()).isEmpty()){
					_idSound = listSound.get(position).getVpssId();
					_position = position;					
					
					listView.focusableViewAvailable(arg1);
					//listView.setSelection(position);
					//listView.setChoiceMode(position);					

					try {
						onStopSound();
						Thread.sleep(100);						
					} catch (InterruptedException e) {					
						e.printStackTrace();
					};	
					onStartSound(_position);
					
					list_adapter.setMyLastSelectedPostition(_position);
					
					listView.setSelection(_position);
					listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
					listView.setItemChecked(_position, true);
				}
			}
		});	
		
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				_idSound = listSound.get(position).getVpssId();
				_position = position;
				
				registerForContextMenu(listView);
				return false;
			}
		});
		if (listSound.size() >0){		
		}
	}
		
	//Menu in Action bar
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		getMenuInflater().inflate(R.menu.vpsnooze_sound, menu);				
		return true;
	}
	
	//Contect menu when list long click
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
		super.onCreateContextMenu(menu, v, menuInfo);		
		getMenuInflater().inflate(R.menu.vpcontact_context, menu);
		menu.setHeaderTitle(R.string.ctx_action_title);
				
	}
	
	public boolean onContextItemSelected(MenuItem item){
		switch (item.getItemId()) {
		
		case R.id.ctm_edit:
			
			break;
		case R.id.ctm_delete:
			 soundBL.deleteSoundbyID(_position);
			 listSound.remove(_position);
			 list_adapter = new  ListViewSnoozeSoundAdapter(listSound,this);
			 list_adapter.notifyDataSetChanged();
			 listView.setAdapter(list_adapter);
			 listView.invalidateViews();
			break;
			
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	public boolean onOptionsItemSelected(MenuItem v){
		switch (v.getItemId()) {
		case R.id.action_add:		
		//	StartRecordAudio();
			showDialogCustom();
			break;

		default:
			break;
		}
		return true;
		
	}
	
	public void showDialogCustom(){
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final String[] element = new String[]{"Get from directory", "Record new"};
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, element);
		alert.setTitle("Snooze Sound");
		alert.setAdapter(adapter, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (element[which].contains("Get from directory")) {
					StartAudioDir();
				}
				else {
					//startRecording();
					StartRecordAudio();
				}
				
			}
		});
		alert.show();
	}
	
	public void StartAudioDir(){
		Intent  intent = new Intent();
		intent.setType("music/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Audio File"), SOUND_SELECT);
		
	}
	public void StartRecordAudio(){		
		Intent intent =	new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
			 //  startActivityForResult(intent, SOUND_RECORD);
		if (isAvailable(getApplicationContext(), intent))
		{	
		    startActivityForResult(intent, SOUND_RECORD);
		   
		}
		else
		{
			
			startRecording();
		}
	}
	public void startRecording(){
		MediaRecorder record = new MediaRecorder();
		if(record!=null){
			record.release();
		}
		File file = new File(Environment.getExternalStorageDirectory(),
				   "tmp_audio_" + String.valueOf(System.currentTimeMillis()) + ".wav");
		record.setAudioSource(AudioSource.MIC);
		record.setOutputFormat(OutputFormat.THREE_GPP);
		record.setAudioEncoder(AudioEncoder.AMR_WB);
		record.setOutputFile(file.getAbsolutePath());
		try{
			record.prepare();
			record.start();
		} catch (IOException e) {
				   
			
				  }
		
	}
	public static boolean isAvailable(Context ctx, Intent intent) {
			   final PackageManager mgr = ctx.getPackageManager();
			   List<ResolveInfo> list =
			      mgr.queryIntentActivities(intent, 
			         PackageManager.MATCH_DEFAULT_ONLY);
			   return list.size() > 0;
			}
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);			
		
		if (resultCode == RESULT_OK ){
			uriSound = data.getData();
			FileName = uriSound.getLastPathSegment();	
			switch (requestCode) {
			case SOUND_SELECT:
				int id = soundBL.getNewSoundId();
				File f = new File(uriSound.getPath());
				long size = f.length();
							VPSnoozeSound sound = new VPSnoozeSound(id, 
														FileName, 
														"Y", 
														null,
														size);
				soundBL.addSound(sound);
				//copy sound 
				try {
					copySoundFile(getPathSoud(uriSound), path+"sounds/", FileName);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				listSound.add(sound);
				list_adapter = new ListViewSnoozeSoundAdapter(listSound, this);
				list_adapter.notifyDataSetChanged();
				listView.setAdapter(list_adapter);
				listView.invalidateViews();
			
				break;
			case SOUND_RECORD:
			
				final int idrecord = soundBL.getNewSoundId();
			
				try {
					copySoundFile(getPathSoud(uriSound), path+"sounds/", FileName);
				} catch (IOException e) {					
					e.printStackTrace();
				}
				/*
				 * Hien thi Alert
				 * */
				AlertDialog.Builder alert = new AlertDialog.Builder(this);
		        alert.setTitle("Rename");       
		        final EditText input  = new EditText(this);          
		        input.setText(FileName);
		        alert.setView(input);
		        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						//Toast.makeText(getApplicationContext(), "Current File Name:"+FileName, Toast.LENGTH_LONG).show();
						String value = input.getText().toString().trim();
						File from      = new File(path+"sounds/", FileName);
					    File to        = new File(path+"sounds/", value);
					    boolean renameSuccess = from.renameTo(to);		
					    VPSnoozeSound soundrecord = new VPSnoozeSound(idrecord, 
					    		value, 
								"Y", 
								null,
								to.length());
						soundBL.addSound(soundrecord);
						//
						listSound.add(soundrecord);
						list_adapter = new ListViewSnoozeSoundAdapter(listSound, getApplicationContext());
						list_adapter.notifyDataSetChanged();
						listView.setAdapter(list_adapter);
						listView.invalidateViews();	
					}
				});
		        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();						
					}
		        });
		        alert.show();	        	
								
				break;
			default:				
				break;
			}
		}
	}
	public byte[] getSoundFile(Uri urisound) throws IOException {
		
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		InputStream input = getContentResolver().openInputStream(urisound);
		byte [] byteResult = null;
		try{
			int buffersize = 10240;
			byte [] bytebuffer = new byte[buffersize];
		
			int len = 0;
			while((len = input.read(bytebuffer))!=-1){
				bao.write(bytebuffer,0,len);
			}			
			byteResult	= bao.toByteArray();
		} catch (Exception e){
			Log.v("Message", "Can't tranfer!");
		}
		return byteResult;
	}
	public String getPathSoud(Uri uriSound){		
		try{
			String[] datasound = {MediaStore.Audio.Media.DATA};
			Cursor cur = managedQuery(uriSound, datasound, null, null,null);
			int columnindex = cur.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
			cur.moveToFirst();
			return cur.getString(columnindex);			
		}catch (Exception e){
			return uriSound.getPath();
		}		
	}
	public void copySoundFile(String fullpath, String outputPath, String filename) throws IOException{
		try {
			////Get input file
			InputStream input = new FileInputStream(fullpath);
			///Create new output file
			OutputStream output = new FileOutputStream(outputPath + filename) ;
			//tranfer input file byte to output file
			byte filebyte[] = new byte[2048];
			int length;
			while ((length = input.read(filebyte))>0){
				output.write(filebyte,0,length);
			}
			output.flush();
			output.close();
			input.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	public void showListNamefromDir(String path){
		File file;
		List<String> myList = new ArrayList<String>();		
		file = new File(path);
		File list[] = file.listFiles();
		for (int i = 0; i< list.length;i++){
			myList.add(list[i].getName());
		}		
		
		
	}
	@Override
	protected void onStop() {   
	    super.onStop();
	    if (myPlayer.isPlaying()){
			myPlayer.stop();
			//myPlayer.reset();
			imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play	);						
		}  
	    
	}
	@Override
	protected void onStart(){
		super.onStart();		
	
	}	
	protected void onPause(){
		super.onPause();
		if (myPlayer.isPlaying()){
			positionseek = myPlayer.getCurrentPosition();
			myPlayer.pause();
			
			imagebtnPlay.setBackgroundResource(android.R.drawable.ic_media_play	);		
			
		}		
		
	}
	@Override
	protected void onResume() {
	  super.onResume();	
	  if (positionseek >0){
		  myPlayer.seekTo(positionseek);			              
			myPlayer.start();		
			positionseek = 0;
	  }
	}
	@Override
	public void onBackPressed() {
	    // TODO Auto-generated method stub
	    super.onBackPressed();

	    //Intent intent = new Intent("xper.activity.ACTIVITY_BAR_RESULT_INTENT");
	    //intent.putExtra("codBar", "bar");
	    //setResult(Activity.RESULT_CANCELED, intent);
	    setResult(RESULT_CANCELED);
	    finish();
	}
	@Override
	public void onConfigurationChanged(Configuration config){
		  super.onConfigurationChanged(config);
		  //Action when activity change direction
		   
	}
	
	private class ListViewSnoozeSoundAdapter extends BaseAdapter{
		private Context context;
		private List<VPSnoozeSound> listSound;
		private VPSnoozeSound _sound;	
		private VPSnoozeSound_BL soundBL;
		private ApplicationInformation appInfo;
		private DialogInterface.OnClickListener onClick;
		private int myLastSelectedPostition; 	
		private int sessionID  = 0 ;
		
		private TextView myTvId;
		private TextView myTvPath;
		private ImageView myImage;
		private Switch mySwtchange;
		private TextView myTvSize;
		
		public ListViewSnoozeSoundAdapter(List<VPSnoozeSound> _listSound, Context _context){
			listSound = _listSound;
			context =  _context;
			myLastSelectedPostition = -1;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listSound.size();
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listSound.get(position);
		}
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return listSound.get(position).getVpssId();
		}
		
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View listView = null;
			convertView = null;	
			
			
			
			//path = appInfo.getDBPath();
			if (convertView ==null){
				listView =  new View(context);
				listView = inflater.inflate(R.layout.activity_vpsnoozesound_sub, null);
				///d
				myTvId  = (TextView)listView.findViewById(R.id.tv_SoundID);
				myTvPath  = (TextView)listView.findViewById(R.id.tv_SoundPath);
				myImage = (ImageView)listView.findViewById(R.id.image_Sound);
				mySwtchange =  (Switch)listView.findViewById(R.id.switch_on);
				myTvSize = (TextView)listView.findViewById(R.id.tv_SoundSize);
				
				_sound = new VPSnoozeSound();
				_sound = (VPSnoozeSound)getItem(position);			
				myTvId.setText(String.valueOf(_sound.getVpssId()));
				/////////////////
				
				myTvPath.setText(_sound.getVpssFilePath());
				Typeface mFont = Typeface.createFromAsset(context.getAssets(), "fonts/times.ttf");
				myTvPath.setTypeface(mFont);
				//
				
				myImage.setImageResource(R.raw.sound_icon);
				//
				
				mySwtchange.setFocusable(false);
				String _status = _sound.getVpssEnableFlag();
				if (_status.equals("Y")){
					mySwtchange.setChecked(true)  ;
					
				}else
				{
					mySwtchange.setChecked(false)  ;
				}
				
				mySwtchange.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					String _status;
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked){
							_status = "Y";
							
						}else
							_status = "N";	
						{

						}
					}
				});
				
				
				myTvSize.setText(Math.round(_sound.getVpssSize()/1024)+"KB");
				
			}
			
			if(position % 2 == 0)
			{
				listView.setBackgroundResource(R.drawable.background_shape_gray);
				myTvPath.setTextColor(Color.BLACK);
				myTvSize.setTextColor(Color.BLACK);
			}
			else
			{
				listView.setBackgroundResource(R.drawable.background_shape_green);
				myTvPath.setTextColor(Color.WHITE);
				myTvSize.setTextColor(Color.WHITE);
			}
			
			if(position == myLastSelectedPostition)
			{
				listView.setBackgroundResource(R.drawable.list_selector_pressed_shape);
				myTvPath.setTextColor(Color.WHITE);
				myTvSize.setTextColor(Color.WHITE);
			}
			
			return listView;		
		}
		
		public void setMyLastSelectedPostition(int myLastSelectedPostition) {
			this.myLastSelectedPostition = myLastSelectedPostition;
		}

		public int getMyLastSelectedPostition() {
			return myLastSelectedPostition;
		}
	}
}
